package aw;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import utils.ReadXMLFile;
import utils.World;
import java.util.HashMap;


public class AlienWorldImpl extends UnicastRemoteObject implements ServerInterface{
	static int _elemsTeam1 = 0;
	static int _elemsTeam2 = 0;
	static String playerIdTurn;
	static Agent playerAgentTurn;
	final static int NUMBER_OF_PLAYERS = 1;
	static ArrayList<Agent> agents = new ArrayList<Agent>();
	static ArrayList<Agent> allAgents = new ArrayList<Agent>();
	private ReadXMLFile r = new ReadXMLFile();
	private World world = null;
	static HashMap<Integer, ArrayList<String>> objectsByRoom = new HashMap<Integer, ArrayList<String>>();

    public AlienWorldImpl() throws RemoteException{
        super();
        world = r.createMap();
        r.printMap(world, agents);
    }

    public boolean Move(String id, String direction) throws RemoteException{
    	if(!id.equals(playerIdTurn))
    		return false;
    	else playerIdTurn = "";
    	
    	
    	String[] pos = playerAgentTurn.getPosition().split("[*]");
    	String[] roomDim = playerAgentTurn.get_roomDim().split("[*]");
    	
    	if(direction.equals("N")){
    		if(Integer.parseInt(pos[1]) == Integer.parseInt(roomDim[1])-1)
    			return false;
    		else pos[1] = ((Integer.parseInt(pos[1]))+1)+"";
    	}else if(direction.equals("S")){
    		if(Integer.parseInt(pos[1]) == 0)
    			return false;
    		else pos[1] = ((Integer.parseInt(pos[1]))-1)+"";
    	}else if(direction.equals("W")){
    		if(Integer.parseInt(pos[0]) == 0)
    			return false;
    		else pos[0] = ((Integer.parseInt(pos[0]))-1)+"";
    	}else if(direction.equals("E")){
    		if(Integer.parseInt(pos[0]) == Integer.parseInt(roomDim[0])-1)
    			return false;
    		else pos[0] = ((Integer.parseInt(pos[0]))+1)+"";
    	}
    	
    	playerAgentTurn.setPosition(pos[0]+"*"+pos[1]);
    	r.printMap(world, agents);
    	return true;
    }
    
    public boolean Catch(String id, String direction) throws RemoteException{
    	if(!id.equals(playerIdTurn))
    		return false;
    	else playerIdTurn = "";
    	//todo
    	return true;//alterar
    }

    public boolean Combine(String id, String objA, String objB) throws RemoteException{
    	if(id != playerIdTurn)
    		return false;
    	else playerIdTurn = "";
		//todo
    	return true;//alterar
	}

    public boolean Use(String id, String direction, String what, String toWhat) throws RemoteException{
    	if(id != playerIdTurn)
    		return false;
    	else playerIdTurn = "";
		//todo
    	return true;//alterar
	}

    public boolean SendMessage(String idSource, String idDestination, String message) throws RemoteException{
    	if(idSource != playerIdTurn)
    		return false;
    	else playerIdTurn = "";
    	//todo
    	return true;//alterar
    }

    public boolean Trade(String id, String offering, String wanting) throws RemoteException{
    	if(id != playerIdTurn)
    		return false;
    	else playerIdTurn = "";
    	//todo
    	return true;//alterar
    }

    public String RegisterAgent(int teamID, AgentInterface agent) throws RemoteException{
    	String id = "";
    	if(teamID == 1){
    		_elemsTeam1++;
    		id = "AG:"+teamID+":"+_elemsTeam1;
    	}
    	else{
    		_elemsTeam2++;
    		id = "AG:"+teamID+":"+_elemsTeam2;
    	}
    	allAgents.add(new Agent(id, teamID, agent, Static_Variables.PosIni.get(0), "0*10", "", 1, "6*6"));
    	Static_Variables.PosIni.remove(0);
    	//idGameReadytoStart();
    	
    	return id;
    }
    
    
    
    
    
    
    
    
    
    
    public static void idGameReadytoStart(){
    	while(true){
    	if (_elemsTeam1 == NUMBER_OF_PLAYERS && _elemsTeam2 == NUMBER_OF_PLAYERS){
    		for(int i=0, a=0, b=0; i < (_elemsTeam1 + _elemsTeam2); i+=2){
    			while(true){
    				if(allAgents.get(a).get_team() == 1)
    					break;
    				else a++;
    			}
    			agents.add(allAgents.get(a));
    			a++;
    			
    			while(true){
    				if(allAgents.get(b).get_team() == 2)
    					break;
    				else b++;
    			}
    			agents.add(allAgents.get(b));
    			b++;
    		}
    		
    		System.out.println("o jogo ta pronto a come�ar :D, num de jogadore:"+agents.size());
    		
    		robotCicle();
    		return;
    	}else{
    		try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    	}
    }
    
    static boolean isGameFinished(){
    	if(agents.size() == 0)
    		return false;
    	else return true;
    }
    
    public static void robotCicle(){
    	
		Agent ag;
    	do{
    		String agentsPositions = "";
    		String objectsPositions = ""; //FALTA FAZER...............................
    		String roomSize = ""; //FALTA FAZER...............................
    		
    		for (int i = 0; i < agents.size(); i++) {
    			ag=agents.get(i);
    			agentsPositions += ag.get_id()+"-"+ag.getPosition()+"#";
    		}
    		for (int i = 0; i < agents.size(); i++) {
				if(i == 0){
					ag = agents.get(i);
					try {
						playerIdTurn = ag.get_id();
						playerAgentTurn = ag;
						ag.get_reference().Update(agentsPositions, objectsPositions, roomSize, ag.get_agentState(), ag.get_agentCollection(), true);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}else{
					ag = agents.get(i);
					try {
						ag.get_reference().Update(agentsPositions, objectsPositions, roomSize, ag.get_agentState(), ag.get_agentCollection(), false);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
    		
    		ag = agents.get(0);
    		String[] state = ag.get_agentState().split("[*]");
    		ag.set_agentState(state[0]+"*"+(Integer.parseInt(state[1])-1));
    		
    		if((Integer.parseInt(state[1])-1) <=0 ){
    			//dizer ao gajo k morreu
    			try {
					ag.get_reference().Dead();
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			agents.remove(0);
    		}else{
        		agents.remove(0);
        		agents.add(ag);
    		}
    		
    		while(playerIdTurn != ""){
	    		try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
    		}
    		
    		
    		//todo
    	}while(isGameFinished());   
    	int goldT1 = 0;
    	int goldT2 = 0;
    	int winnerID;
    	for(int i = 0; i < allAgents.size(); i++){
    		ag = allAgents.get(i);
    		if(ag.get_team() == 1){
    			goldT1 += Integer.parseInt(ag.get_agentState().split("[*]")[0]);
    		}else{
    			goldT2 += Integer.parseInt(ag.get_agentState().split("[*]")[0]);
    		}    			
    	}
    	if(goldT1 > goldT2)
    		winnerID=1;
    	else winnerID=2;
    	
    	
    	for(int i = 0; i < allAgents.size(); i++){
    		ag = allAgents.get(i);
    		try {
				ag.get_reference().GameOver(winnerID);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	return;
    }
    
    
    
    
    
}
